package 数组.二分查找.首位位置;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/1/11 9:55
 * @description:给你一个按照非递减顺序排列的整数数组 nums，和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        int[] arr = {1,2,2,3,3,3,4,5,6};
        int target = 3;
        searchRange2(arr,target);
    }

    //二分法
    public static int[] searchRange(int[] nums, int target) {
        int[] result = {-1,-1};
        int left = 0;
        int right = nums.length - 1;
        int mid ;
        while (left <= right){
            mid = left + (right - left) / 2;
            if (nums[mid] == target){
                result[0] = mid;
                result[1] = mid;
                while (nums[mid] == target ){
                    result[0] = mid;
                    mid--;
                    if (mid < left){
                        mid++;
                        break;
                    }
                }
                mid = result[0];
                while (nums[mid] == target ){
                    result[1] = mid;
                    mid++;
                    if (mid > right){
                        mid--;
                        break;
                    }
                }
                break;
            }else if (nums[mid] < target){
                left = mid + 1;
            }else {
                right = mid - 1;
            }
        }
        return result;
    }


    //官方解法
    public static int[] searchRange2(int[] nums, int target) {
        int i = find(nums, target, true);
        int j = find(nums, target, false);
        return new int[]{i,j};
    }

    public static int find(int[] nums, int target, boolean minType) {
        int left = 0, right = nums.length - 1;
        int ans = -1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                ans = mid;
                if (minType) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } else if (target < nums[mid]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return ans;
    }



}
